import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { GUI } from 'three/examples/jsm/libs/lil-gui.module.min.js'

// 渲染器、相机和场景
let initCamera, scene, initRenderer, cube

function renderer() {
  scene = new THREE.Scene()

  // 获取 canvas 元素
  const canvas = document.querySelector('#c')
  if (!canvas) {
    console.error('No canvas element found with id "c".')
    return
  }

  // 创建渲染器，指定 canvas 元素
  initRenderer = new THREE.WebGLRenderer({ antialias: true, canvas })
  initRenderer.setSize(window.innerWidth, window.innerHeight)
  document.body.appendChild(initRenderer.domElement)
}

function camera() {
  initCamera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000)
  initCamera.position.set(1, 1, 1)
  initCamera.lookAt(0, 0, 0)
  scene.add(initCamera)
}

function createObj() {
  const geometry = new THREE.BoxGeometry(1, 1, 1)
  const material = new THREE.MeshBasicMaterial({ color: 0xffff00 })
  cube = new THREE.Mesh(geometry, material)
  scene.add(cube)
}

function initGui() {
  const gui = new GUI()
  const obj = { scale: 1 }
  gui
    .add(obj, 'scale')
    .min(0)
    .max(10) // 设置最大值
    .step(0.1) // 设置步长
    .onChange(value => {
      cube.scale.set(value, value, value) // 调整立方体的缩放
    })
}

function init() {
  renderer()
  createObj()
  camera()
  initGui()

  // 创建控制器
  const controls = new OrbitControls(initCamera, initRenderer.domElement)
  controls.update() // 使控制器在初始时生效

  // 渲染循环
  function animate() {
    requestAnimationFrame(animate)
    initRenderer.render(scene, initCamera)
  }
  animate()
}

// 响应窗口大小变化
window.addEventListener('resize', onWindowResize)
function onWindowResize() {
  // 更新相机的宽高比
  initCamera.aspect = window.innerWidth / window.innerHeight
  initCamera.updateProjectionMatrix()

  // 更新渲染器的尺寸
  initRenderer.setSize(window.innerWidth, window.innerHeight)
}

init()
window.scene = scene
